﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;

namespace XingWeiDaWMSProject.Controllers
{
    public class StockInController : Controller
    {
        private readonly IInboundOrderService _inboundOrderService;

        // 注入入库单服务
        public StockInController(IInboundOrderService inboundOrderService)
        {
            _inboundOrderService = inboundOrderService;
        }
        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        public IActionResult AddPage()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        /// <summary>
        /// 新增入库单（含明细）- 匹配前端接口调用路径
        /// </summary>
        [HttpPost("api/InboundOrder/Add")]
        public async Task<IActionResult> AddInboundOrder([FromBody] InboundOrderRequest request)
        {
            try
            {
                // 1. 基础参数校验
                if (string.IsNullOrWhiteSpace(request.warehouse_receipt_no))
                    return Json(new { success = false, message = "入库单号不能为空" });
                if (string.IsNullOrWhiteSpace(request.storage_type))
                    return Json(new { success = false, message = "入库类型不能为空" });
                if (request.warehouse_id == null || request.warehouse_id <= 0)
                    return Json(new { success = false, message = "请选择有效的仓库" });
                if (string.IsNullOrWhiteSpace(request.date_of_storage))
                    return Json(new { success = false, message = "入库日期不能为空" });
                if (request.suppliers_id <= 0)
                    return Json(new { success = false, message = "请选择有效的供应商" });
                if (request.handler_id <= 0)
                    return Json(new { success = false, message = "请选择有效的经办人" });
                if (request.details == null || request.details.Count == 0)
                    return Json(new { success = false, message = "至少添加一条入库明细" });
                if (request.details.Any(d => d.inbound_quantity <= 0))
                    return Json(new { success = false, message = "入库数量必须大于0" });

                // 2. 构造主表实体
                var order = new InboundOrderEntity
                {
                    warehouse_receipt_no = request.warehouse_receipt_no,
                    warehouse_id = request.warehouse_id,
                    rule_id = request.rule_id,
                    type_id = request.type_id,
                    storage_type = request.storage_type,
                    warehouse_name = request.warehouse_name,
                    storage_status = "2", 
                    date_of_storage = DateTime.Parse(request.date_of_storage),
                    associated_order_no = request.associated_order_no,
                    suppliers_id = request.suppliers_id,
                    handler_id = request.handler_id,
                    organizations_id = request.organizations_id,
                    note = request.note,
                    create_by = "admin", // 实际应从登录上下文获取
                    create_time = DateTime.Now,
                    is_delete = "0"
                };

                var details = request.details.Select(d => new InboundOrderDetailEntity2
                {
                    product_code = d.product_code,
                    curr_stk_in_num = d.inbound_quantity,
                    storage_location = d.inbound_location,
                    batch_number = d.batch_no,
                    Production_date = string.IsNullOrWhiteSpace(d.production_date)
                    ? null
                    : DateTime.Parse(d.production_date),
                    note = d.note,
                    unit_price = d.unit_price, // 若前端无单价，设为0（或从业务逻辑获取）
                    create_by = order.create_by,
                    create_time = order.create_time,
                    update_by = order.create_by,
                    update_time = order.create_time,
                    is_delete = "0"
                }).ToList();

                await _inboundOrderService.AddInboundOrderAsync2(order, details);

                return Json(new { success = true, message = "入库单新增成功" });
            }
            catch (ArgumentException ex)
            {
                return Json(new { success = false, message = ex.Message });
            }
            catch (Exception ex)
            {
                return Json(new { success = false, message = $"服务器错误：{ex.Message}" });
            }
        }

        /// <summary>
        /// 入库单草稿保存（与新增逻辑一致，仅状态区分）
        /// </summary>
        [HttpPost("api/InboundOrder/SaveDraft")]
        public async Task<IActionResult> SaveDraft([FromBody] InboundOrderRequest request)
        {
            // 强制设置为草稿状态
            request.storage_status = "0";
            return await AddInboundOrder(request);
        }

        /// <summary>
        /// 入库单审核接口
        /// </summary>
        /// <param name="request">审核请求参数</param>
        [HttpPost("/api/StockIn/Audit")]
        public async Task<IActionResult> Audit([FromBody] AuditRequest request)
        {
            try
            {
                // 1. 从Session获取当前登录人
                string currentUser = HttpContext.Session.GetString("LoginUserName");
                if (string.IsNullOrEmpty(currentUser))
                {
                    return Ok(new { success = false, message = "未获取到登录信息，请重新登录" });
                }

                // 2. 覆盖审核人（确保使用当前登录人，忽略前端可能传递的值）
                request.Reviewer = currentUser;

                // 3. 执行审核逻辑
                await _inboundOrderService.AuditInboundOrderAsync(request);
                return Ok(new { success = true, message = "审核操作成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { success = false, message = ex.Message });
            }
        }

    }
}
